package com.yuqing.sentimentapp.workspace.epidemic.material;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.PopupMenu;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.linkface.baselibrary.utils.DateUtil;
import com.linkface.baselibrary.utils.FileUtils;
import com.linkface.baselibrary.utils.ThreadManager;
import com.yuqing.sentimentapp.R;
import com.yuqing.sentimentapp.base.BaseActivity;
import com.yuqing.sentimentapp.base.BaseObserver;
import com.yuqing.sentimentapp.login.bean.LoginResultBean;
import com.yuqing.sentimentapp.module.DownloadPdfHelp;
import com.yuqing.sentimentapp.module.ModuleManager;
import com.yuqing.sentimentapp.utils.IntantUtil;
import com.yuqing.sentimentapp.utils.SharePrefrenceHelper;
import com.yuqing.sentimentapp.utils.ToastUtil;
import com.yuqing.sentimentapp.workspace.duty.entity.ReportUnitInfoResult;
import com.yuqing.sentimentapp.workspace.epidemic.material.entity.EpidemicMaterialInfoResult;
import com.yuqing.sentimentapp.workspace.epidemic.material.entity.EpidemicMaterialReportResult;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.DateTimePicker;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class EpidemicMaterialReportActivity extends BaseActivity{
    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.iv_download)
    ImageView mIvDownload;
    @BindView(R.id.iv_report)
    ImageView mIvReport;
    @BindView(R.id.tv_today_reported_num)
    TextView mTvTodayReportedNum;
    @BindView(R.id.tv_today_reported)
    TextView mTvTodayReported;
    @BindView(R.id.rl_reported)
    RelativeLayout mRlReported;
    @BindView(R.id.iv_to_report)
    ImageView mIvToReport;
    @BindView(R.id.tv_today_to_report_num)
    TextView mTvTodayToReportNum;
    @BindView(R.id.tv_today_to_report)
    TextView mTvTodayToReport;
    @BindView(R.id.rl_to_report)
    RelativeLayout mRlToReport;
    @BindView(R.id.tv_fill_in)
    TextView mTvFillIn;
    @BindView(R.id.tv_reporting_unit)
    TextView mTvReportingUnit;
    @BindView(R.id.ll_reporting_unit)
    LinearLayout mLlReportingUnit;
    @BindView(R.id.tv_start_time)
    TextView mTvStartTime;
    @BindView(R.id.tv_end_time)
    TextView mTvEndTime;
    @BindView(R.id.tv_export)
    TextView mTvExport;
    @BindView(R.id.ll_start_time)
    LinearLayout mLlStartTime;
    @BindView(R.id.ll_end_time)
    LinearLayout mLlEndTime;
    @BindView(R.id.rg_unit)
    RadioGroup mRgUnit;
    @BindView(R.id.rb_1)
    RadioButton mRadio1;
    @BindView(R.id.rb_2)
    RadioButton mRadio2;
    @BindView(R.id.ll_export_unit)
    LinearLayout mLlExportUnit;
    private ArrayList<EpidemicMaterialReportResult.DataBean.ReportsBean> toReportBeanList = new ArrayList<>();
    private ArrayList<EpidemicMaterialReportResult.DataBean.ReportsBean> reportedBeanList = new ArrayList<>();
    private List<ReportUnitInfoResult.DataBean.DeptsBean> reportUnitInfo;
    private EpidemicMaterialInfoResult.DataBean edpiemicInfo;
    private String level;
    private EpidemicMaterialReportResult.DataBean.SubSumBean subSum;
    private String deptLevel = "";

    public static void goActivity(Activity activity) {
        Intent intent = new Intent(activity, EpidemicMaterialReportActivity.class);
        activity.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_epidemic_material_report;
    }

    @Override
    public void initPresenter() {
        LoginResultBean.DataBean.UserBean user = SharePrefrenceHelper.getUser();

        if (user != null && user.getDeptVo() != null) {
            deptLevel = user.getDeptVo().getDeptLevel();
        }
        /**
         * 总队身份显示导出单位，其他身份隐藏，并给level赋默认值
         */
        if (TextUtils.equals("1", deptLevel)) {
            mLlExportUnit.setVisibility(View.VISIBLE);
        } else {
            mLlExportUnit.setVisibility(View.GONE);
            level = TextUtils.equals("0", deptLevel) ? "1" : "2";
        }

        /**
         * 部局身份隐藏填报
         */
        if (TextUtils.equals("0", deptLevel)) {
            mTvFillIn.setVisibility(View.GONE);
        } else {
            mTvFillIn.setVisibility(View.VISIBLE);
        }

        /**
         * 支队身份今日上报信息置灰，不可点击并隐藏下载
         */
        if (TextUtils.equals("2", deptLevel)) {
            mIvDownload.setVisibility(View.GONE);
            mRlReported.setBackgroundColor(getResources().getColor(R.color.color_F6F6F6));
            mRlToReport.setBackgroundColor(getResources().getColor(R.color.color_F6F6F6));
            mRlToReport.setClickable(false);
        } else {
            mIvDownload.setVisibility(View.VISIBLE);
            mRlReported.setBackgroundColor(getResources().getColor(R.color.white));
            mRlToReport.setBackgroundColor(getResources().getColor(R.color.white));
            mRlToReport.setClickable(true);
        }

        /**
         * 开始时间默认从前3天开始
         */
        mTvStartTime.setText(DateUtil.getFormatDate(DateUtil.getDateBefore(new Date(), 3), DateUtil.DATE_FORMAT));
    }

    @Override
    public void initView() {
//        presenter.getReportUnit();
        mRgUnit.setOnCheckedChangeListener((group, checkedId) -> {
            Object tag = ((RadioButton) findViewById(checkedId)).getTag();
            if (tag == null) return;
            level = tag.toString();
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getTodayInfo();
        getReportInfo("");
    }

    private void getReportInfo(String id) {
        ModuleManager.getInstance().requestEpidemicMaterialReportInfoResult(id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<EpidemicMaterialInfoResult>() {
                    @Override
                    protected void hideDialog() {
                        stopProgressDialog();
                    }

                    @Override
                    protected void showDialog() {
                        startProgressDialog();
                    }

                    @SuppressLint("CheckResult")
                    @Override
                    protected void onSuccess(EpidemicMaterialInfoResult result) {
                        if (result == null) return;
                        edpiemicInfo = result.getData();
                    }

                    @Override
                    protected void onFailure(String message) {
//                        ToastUtil.showShort(message);
                    }
                });
    }

    private void getTodayInfo() {
        ModuleManager.getInstance().requestEpidemicMaterialTodayInfoResult()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<EpidemicMaterialReportResult>() {
                    @Override
                    protected void hideDialog() {
                        stopProgressDialog();
                    }

                    @Override
                    protected void showDialog() {
                        startProgressDialog();
                    }

                    @SuppressLint("CheckResult")
                    @Override
                    protected void onSuccess(EpidemicMaterialReportResult epidemicMaterialReportResult) {
                        subSum = epidemicMaterialReportResult.getData().getSubSum();
                        List<EpidemicMaterialReportResult.DataBean.ReportsBean> reports = epidemicMaterialReportResult.getData().getReports();
                        Observable.fromIterable(reports)
                                .filter(reportsBean -> TextUtils.isEmpty(reportsBean.getId())).toList()
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(reportsBeans -> {
                                    toReportBeanList.clear();
                                    toReportBeanList.addAll(reportsBeans);
                                    int toReportsize = reportsBeans.size();
                                    int reportedSize = reports.size() - toReportsize;
                                    mTvTodayReportedNum.setText(reportedSize + "");
                                    mTvTodayToReportNum.setText(toReportsize + "");

                                    reports.removeAll(toReportBeanList);
                                    reportedBeanList.clear();
                                    reportedBeanList.addAll(reports);
                                });
                    }

                    @Override
                    protected void onFailure(String message) {
                        ToastUtil.showShort(message);
                    }
                });
    }

    @OnClick({R.id.iv_back, R.id.iv_download, R.id.rl_to_report, R.id.rl_reported, R.id.tv_fill_in, R.id.ll_reporting_unit, R.id.tv_export, R.id.ll_start_time, R.id.ll_end_time})
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_download:
                /**
                 * 部局、总队身份，不用填报就能下载，支队必须填报后才能下载
                 */
                if (edpiemicInfo == null && TextUtils.equals(deptLevel, "2")) {
                    showShortToast("请先填报信息");
                    return;
                }
                exportEpidemicTodayReportInfo();
                break;
            case R.id.rl_reported:
                if (reportedBeanList == null || reportedBeanList.size() <= 0) return;
                ToEpidemicMaterialActivity.goActivity(EpidemicMaterialReportActivity.this, reportedBeanList, true);
                break;
            case R.id.rl_to_report:
                if (toReportBeanList == null || toReportBeanList.size() <= 0) return;
                ToEpidemicMaterialActivity.goActivity(EpidemicMaterialReportActivity.this, toReportBeanList, false);
                break;
            case R.id.tv_fill_in:
                EpidemicMaterialFillInActivity.goActivity(EpidemicMaterialReportActivity.this, edpiemicInfo, subSum);
                break;
            case R.id.ll_reporting_unit:
                if (reportUnitInfo == null || reportUnitInfo.size() == 0) return;
                PopupMenu popupMenu = new PopupMenu(this, mTvReportingUnit);
                Menu menu_more = popupMenu.getMenu();

                for (int i = 0; i < reportUnitInfo.size(); i++) {
                    menu_more.add(Menu.NONE, i, i, reportUnitInfo.get(i).getDeptName());
                }
                popupMenu.setOnMenuItemClickListener(menuItem -> {
                    int i = menuItem.getItemId();
                    mTvReportingUnit.setText(reportUnitInfo.get(i).getDeptName());
                    mTvReportingUnit.setTag(reportUnitInfo.get(i).getDeptCode());
                    return true;
                });
                popupMenu.show();
                break;
            case R.id.tv_export:
                String from = TextUtils.isEmpty(mTvStartTime.getText().toString()) ? "" : mTvStartTime.getText().toString();
                String to = TextUtils.isEmpty(mTvEndTime.getText().toString()) ? "" : mTvEndTime.getText().toString();
                if (TextUtils.equals("1", deptLevel) && mRgUnit.getCheckedRadioButtonId() == -1) {
                    showShortToast("请选择导出单位");
                    return;
                }
                exportEpidemicMaterialHistoryReportInfo(level,from,to);
                break;
            case R.id.ll_start_time:
                showTimeSelectorView(0);
                break;
            case R.id.ll_end_time:
                showTimeSelectorView(1);
                break;
        }
    }

    private void exportEpidemicMaterialHistoryReportInfo(String level, String from, String to) {
        //建立一个文件
        File mFile = new File(DownloadPdfHelp.PATH_CHALLENGE_PDF + File.separator + "epidemic_material" + File.separator + "report_history.xls");

        if (!FileUtils.isFileExists(mFile)) {
            mFile.getParentFile().mkdirs();
            try {
                mFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (TextUtils.isEmpty(DownloadPdfHelp.PATH_CHALLENGE_PDF)) {
            return;
        }
        startProgressDialog();
        Call<ResponseBody> mCall = ModuleManager.getInstance().exportEpidemicMaterialHistoryReportInfoResult(level, from, to);
        mCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(@NonNull Call<ResponseBody> call, @NonNull final Response<ResponseBody> response) {
                ThreadManager.getThreadPollProxy().execute(() -> {
                    //保存到本地
                    writeFile2Disk(response, mFile);
                });
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                showShortToast("导出失败");
                stopProgressDialog();
            }
        });
    }

    private void exportEpidemicTodayReportInfo() {
        //建立一个文件
        File mFile = new File(DownloadPdfHelp.PATH_CHALLENGE_PDF + File.separator + "epidemic_material" + File.separator + "report_today.xls");

        if (!FileUtils.isFileExists(mFile)) {
            mFile.getParentFile().mkdirs();
            try {
                mFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (TextUtils.isEmpty(DownloadPdfHelp.PATH_CHALLENGE_PDF)) {
            return;
        }
        startProgressDialog();
        Call<ResponseBody> mCall = ModuleManager.getInstance().exportEpidemicMaterialTodayReportInfoResult();
        mCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(@NonNull Call<ResponseBody> call, @NonNull final Response<ResponseBody> response) {
                ThreadManager.getThreadPollProxy().execute(() -> {
                    //保存到本地
                    writeFile2Disk(response, mFile);
                });
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                showShortToast("导出失败");
                stopProgressDialog();
            }
        });
    }

    //将下载的文件写入本地存储
    private void writeFile2Disk(Response<ResponseBody> response, File file) {
        long currentLength = 0;
        OutputStream os = null;
        if (response.body() == null) {
            runOnUiThread(() -> {
                showShortToast("导出数据不存在，请重试");
                stopProgressDialog();
            });
            return;
        }
        InputStream is = response.body().byteStream(); //获取下载输入流
        long totalLength = response.body().contentLength();

        try {
            os = new FileOutputStream(file); //输出流
            int len;
            byte[] buff = new byte[1024];
            while ((len = is.read(buff)) != -1) {
                os.write(buff, 0, len);
                currentLength += len;
                //计算当前下载百分比，并经由回调传出
                //当百分比为100时下载结束，调用结束回调，并传出下载后的本地路径
                if ((int) (100 * currentLength / totalLength) == 100) {
                    runOnUiThread(() -> {
                        showLongToast(file.getAbsolutePath() + " 导出成功");
                        try {
                            Intent excelFileIntent = IntantUtil.getExcelFileIntent(file);
                            startActivity(excelFileIntent);
                        } catch (Exception e) {
                            showLongToast("未找到能打开此文件的应用");
                        }
                    });
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close(); //关闭输出流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close(); //关闭输入流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            runOnUiThread(this::stopProgressDialog);
        }
    }

    private void showTimeSelectorView(int type) {
        DateTimePicker picker = new DateTimePicker(this, DateTimePicker.NONE);//24小时值
        picker.setDateRangeStart(1910, 1, 1);//日期起点
        picker.setDateRangeEnd(2099, 1, 1);//日期终点
        picker.setTextColor(getResources().getColor(R.color.color_0d7dff), getResources().getColor(R.color.color_666666));
        picker.setCancelTextColor(getResources().getColor(R.color.color_0d7dff));
        picker.setSubmitTextColor(getResources().getColor(R.color.color_0d7dff));
        picker.setLineColor(getResources().getColor(R.color.color_0d7dff));
        picker.setOnDateTimePickListener((DateTimePicker.OnYearMonthDayTimePickListener) (year, month, day, hour, minute) -> {
            //year:年，month:月，day:日，hour:时，minute:分
            String time = year + "-" + month + "-" + day;
            switch (type) {
                case 0:
                    mTvStartTime.setText(time);
                    break;
                case 1:
                    mTvEndTime.setText(time);
                    break;
            }
        });
        picker.show();
    }
}
